package com.ksyun.player.now;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.PixelFormat;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;

import com.ksyun.player.now.activity.LiveDisplayActivity;
import com.ksyun.player.now.activity.SettingNewActivity;
import com.ksyun.player.now.activity.VodDisplayActivity;
import com.ksyun.player.now.model.FloatingPlayer;
import com.ksyun.player.now.utils.Config;
import com.ksyun.player.now.view.FloatWindowView;


public class MainActivity extends AppCompatActivity implements Handler.Callback, View.OnClickListener {

    private static final int OVERLAY_PERMISSION_RESULT_CODE = 170;
    public static final int REMOVE_FLOATING_WINDOW = 1111;
    public static final int STOP_FLOATING_WINDOW = REMOVE_FLOATING_WINDOW + 1;
    public static final int ONLY_REMOVE_WINDOW = REMOVE_FLOATING_WINDOW + 2;
    public static final int DATA_RESPONSE = REMOVE_FLOATING_WINDOW + 3;
    public static final int NETWORK_ERROR = REMOVE_FLOATING_WINDOW + 4;
    private Boolean toDisplay = false;

    private FloatWindowView mFloatingView;
    private WindowManager.LayoutParams mFloatingViewParams;
    private WindowManager mWindowManager;


    private Handler mHandler;
    private SharedPreferences mSettings;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_choose);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
        initView();
        checkPermission();
        mHandler = new Handler(getMainLooper(), this);
        mSettings = getSharedPreferences("SETTINGS", Context.MODE_PRIVATE);
    }

    private void initView() {
        findViewById(R.id.llt_dianbo).setOnClickListener(this);
        findViewById(R.id.llt_setting).setOnClickListener(this);
        findViewById(R.id.llt_zhibo).setOnClickListener(this);
    }

    private void checkPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(this)) {
            Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                    Uri.parse("package:" + getPackageName()));
            startActivityForResult(intent, OVERLAY_PERMISSION_RESULT_CODE);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == OVERLAY_PERMISSION_RESULT_CODE) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
                if (!Settings.canDrawOverlays(this))
                    Toast.makeText(this, "Permission SYSTEM_ALERT_WINDOW not granted", Toast.LENGTH_SHORT).show();
        }
    }

    private boolean isLive = false;

    @Override
    public void onClick(View view) {
        int i = view.getId();
        if (i == R.id.llt_dianbo) {
            isLive = false;
            Intent intent = new Intent(this, VodDisplayActivity.class);
            intent.putExtra(Config.RUL, "https://ks3-cn-beijing.ksyun.com/ksvsdemo/xulei_0815/Aerial%2520China%25206-libx264-1280x720-1100000.mp4");
            intent.putExtra(Config.TITLE, "航拍中国·上海");
            startActivity(intent);
        } else if (i == R.id.llt_zhibo) {
            isLive = false;
            Intent intent = new Intent(this, LiveDisplayActivity.class);
            intent.putExtra(Config.RUL, "http://nemo.hdllive.ks-cdn.com/live/appdemo_328.flv");
            intent.putExtra(Config.TITLE, "YY直播间");
            startActivity(intent);
        } else if (i == R.id.llt_setting) {
            startActivity(new Intent(this, SettingNewActivity.class));
        }
    }


    @Override
    protected void onRestart() {
        super.onRestart();
        mSettings = getSharedPreferences("SETTINGS", Context.MODE_PRIVATE);
        if (FloatingPlayer.getInstance().getKSYTextureView() != null && mSettings.getBoolean("isPlaying", true)) {
            createFloatingWindow(getApplicationContext());
            FloatingPlayer.getInstance().getKSYTextureView().start();
        }
        toDisplay = false;
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (FloatingPlayer.getInstance().getKSYTextureView() != null && !toDisplay) {
            FloatingPlayer.getInstance().getKSYTextureView().pause();
        }
        removeFloatingWindow(getApplicationContext());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        videoPlayEnd();
    }


    @Override
    public boolean handleMessage(Message message) {
        switch (message.what) {
            case REMOVE_FLOATING_WINDOW:
                removeFloatingWindow(getApplicationContext());
                if (isLive) {
                    Intent intent = new Intent(this, LiveDisplayActivity.class);
                    intent.putExtra(Config.RUL, "http://nemo.hdllive.ks-cdn.com/live/appdemo_328.flv");
                    intent.putExtra(Config.TITLE, "YY直播间");
                    startActivity(intent);
                } else {

                    Intent intent = new Intent(this, VodDisplayActivity.class);
                    intent.putExtra(Config.RUL, "https://ks3-cn-beijing.ksyun.com/ksvsdemo/xulei_0815/Aerial%2520China%25206-libx264-1280x720-1100000.mp4");
                    intent.putExtra(Config.TITLE, "航拍中国·上海");
                    startActivity(intent);
                }
                toDisplay = true;
                break;
            case STOP_FLOATING_WINDOW:
                removeFloatingWindow(getApplicationContext());
                videoPlayEnd();
                toDisplay = false;
                break;
            case ONLY_REMOVE_WINDOW:
                removeFloatingWindow(getApplicationContext());
                toDisplay = true;
                break;
            case NETWORK_ERROR:
                Toast.makeText(MainActivity.this, "网络连接失败", Toast.LENGTH_LONG).show();
                break;

        }
        return false;
    }

    private void createFloatingWindow(Context context) {
        if (context == null)
            return;

        WindowManager windowManager = getWindowManager(context);
        int screenWidth = windowManager.getDefaultDisplay().getWidth();
        int screenHeight = windowManager.getDefaultDisplay().getHeight();
        if (mFloatingView == null) {
            mFloatingView = new FloatWindowView(context);
            mFloatingView.addFloatingWindow(FloatingPlayer.getInstance().getKSYTextureView());
            mFloatingView.setHandler(mHandler);
            if (mFloatingViewParams == null) {
                mFloatingViewParams = new WindowManager.LayoutParams();
                mFloatingViewParams.type = WindowManager.LayoutParams.TYPE_TOAST;
                mFloatingViewParams.format = PixelFormat.RGBA_8888;
                mFloatingViewParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL |
                        WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE |
                        WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED;
                mFloatingViewParams.gravity = Gravity.LEFT | Gravity.TOP;
                mFloatingViewParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
                mFloatingViewParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
                mFloatingViewParams.x = screenWidth;
                mFloatingViewParams.y = screenHeight;
            }

            mFloatingView.updateViewLayoutParams(mFloatingViewParams);
            windowManager.addView(mFloatingView, mFloatingViewParams);
        }
    }

    public void removeFloatingWindow(Context context) {
        if (mFloatingView != null) {
            WindowManager windowManager = getWindowManager(context);
            windowManager.removeView(mFloatingView);
            mFloatingView.removeFloatingWindow(FloatingPlayer.getInstance().getKSYTextureView());
            mFloatingView = null;
        }
    }

    private WindowManager getWindowManager(Context context) {
        if (mWindowManager == null) {
            mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        }
        return mWindowManager;
    }

    private void videoPlayEnd() {
        if (FloatingPlayer.getInstance().getKSYTextureView() != null) {
            FloatingPlayer.getInstance().destroy();
        }
    }

}
